package cn.conac.rc.ofs.rest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.conac.rc.framework.utils.BeanUtils;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.framework.vo.ResultPojo;
import cn.conac.rc.ofs.contsant.Contsants;
import cn.conac.rc.ofs.entity.OrganizationBaseEntity;
import cn.conac.rc.ofs.entity.OrganizationEntity;
import cn.conac.rc.ofs.entity.VHistOrgsInfo2Entity;
import cn.conac.rc.ofs.service.DepartmentService;
import cn.conac.rc.ofs.service.DictionaryService;
import cn.conac.rc.ofs.service.OrgCommonService;
import cn.conac.rc.ofs.service.OrganizationBaseService;
import cn.conac.rc.ofs.service.OrganizationService;
import cn.conac.rc.ofs.service.UserExtService;
import cn.conac.rc.ofs.service.VHistOrgsInfo2Service;
import cn.conac.rc.ofs.vo.DepartmentTreeNodeVo2;
import cn.conac.rc.ofs.vo.OrganizationTreeNodeVo;
import cn.conac.rc.ofs.vo.OrganizationTreeNodeVo2;
import cn.conac.rc.ofs.vo.OrganizationVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RequestMapping(value = "organization/")
@RestController
public class OrganizationController {

	@Autowired
	OrganizationService service;

	@Autowired
	DictionaryService dictionaryService;

	@Autowired
	DepartmentService deptService;

	@Autowired
	OrganizationBaseService orgBaseService;

	@Autowired
	OrgCommonService orgCommonService;
	
	@Autowired
	UserExtService userExtService;
	
	@Autowired
	VHistOrgsInfo2Service vHistOrgsInfo2Service;
	
	@ApiOperation(value = "获取某个地区最近变更的三定信息", httpMethod = "GET", response = OrganizationEntity.class, notes = "根据指定数量NUM获取最近变更的三定信息")
	@RequestMapping(value = "recentOrgs", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findRecentOrgs4App(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "数量限制", required = true) @RequestParam("num") int num,
			@ApiParam(value = "地区code", required = true) @RequestParam("areaCode") String areaCode) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		List<OrganizationEntity> orgList = service.findRecentOrgsByNum(num, areaCode);
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(orgList);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "详情", httpMethod = "GET", response = OrganizationEntity.class, notes = "根据id获取资源详情")
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> detail(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") Integer id) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		OrganizationEntity organization = service.findById(id);
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(organization);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "个数", httpMethod = "POST", response = OrganizationEntity.class, notes = "根据条件获得资源数量")
	@RequestMapping(value = "count", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> count(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrganizationVo vo) throws Exception {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		long cnt = service.count(vo);
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(cnt);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "列表", httpMethod = "POST", response = OrganizationVo.class, notes = "根据条件获得资源列表")
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> list(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrganizationVo vo) throws Exception {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		Page<OrganizationEntity> list = service.list(vo);
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(list);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "新增或者更新数据", httpMethod = "POST", response = OrganizationEntity.class, notes = "保存或者更新部门库")
	@RequestMapping(value = "", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> save(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "保存对象", required = true) @RequestBody OrganizationEntity entity) throws Exception {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();

		// 数据格式校验
		String valMsg = service.validate(entity);
		if (valMsg != null) {
			result.setCode(ResultPojo.CODE_FORMAT_ERR);
			result.setMsg(valMsg);
			return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
		}
		
		OrganizationEntity originEntityDb = null;
		Integer originParentId = null;
		if(null != entity.getId()) {
			originEntityDb = service.findById(entity.getId());
			if(StringUtils.isNotBlank(entity.getOrgDomainName())) {
				if(StringUtils.isNotBlank(originEntityDb.getOrgDomainName())) {
					if(originEntityDb.getOrgDomainName().contains(Contsants.OFS_COMMA)){
						String[] orgDomainNames =  originEntityDb.getOrgDomainName().split(Contsants.OFS_COMMA);
						int findFlag = 0;
						for(int i=0; i < orgDomainNames.length; i++) {
							if(orgDomainNames[i].equals(entity.getOrgDomainName())) {
								findFlag = 1;
								break;
							}
						}
						if(findFlag == 1) {
							entity.setOrgDomainName(originEntityDb.getOrgDomainName());
						} else {
							entity.setOrgDomainName(originEntityDb.getOrgDomainName() + Contsants.OFS_COMMA  + entity.getOrgDomainName());
						}
						
					} else {
						if(!entity.getOrgDomainName().equals(originEntityDb.getOrgDomainName())) {
							entity.setOrgDomainName(originEntityDb.getOrgDomainName() + Contsants.OFS_COMMA  + entity.getOrgDomainName());
						}
					}
				}
			} else {
				if(StringUtils.isNotBlank(originEntityDb.getOrgDomainName())) {
					entity.setOrgDomainName(originEntityDb.getOrgDomainName());
				}
			}
			originParentId = originEntityDb.getParentId();
			if(StringUtils.isBlank(entity.getSiUserCode())) {
				if(StringUtils.isNotBlank(originEntityDb.getSiUserCode())) {
					entity.setSiUserCode(originEntityDb.getSiUserCode());
				}
			}
		}
		
		Integer currParentId = entity.getParentId();
		Integer currId = entity.getId();
		
		service.save(entity);
		
		if( null != originEntityDb) {
			service.updateHasChildCol(currParentId, originParentId, currId);
		} else {
			service.updateHasChildCol(currParentId, null, currId);
		}
		
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(entity);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "物理删除部门库及三定信息", httpMethod = "POST", response = OrganizationEntity.class, notes = "根据id物理删除部门库及三定信息")
	@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> delete(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") Integer id) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		String parentId  = null;
		Map<String,Object> resultInfoMap = new HashMap<String,Object>();
		
		OrganizationBaseEntity organizationBaseEntity = orgBaseService.findByOrgId(id);
		if (null == organizationBaseEntity) {
			// 单独删除部门库表
			parentId = orgCommonService.deleteOrganizationInfo(id);
			resultInfoMap.put("id", id);
			if(StringUtils.isNotEmpty(parentId)) {
				service.updateHasChildColByPid(Integer.valueOf(parentId));
				resultInfoMap.put("parentId", parentId);
			}
			
		} else {
			// 删除部门相关的所有表
			List<Integer>  baseIdsList  = new ArrayList<Integer>();
			parentId = orgCommonService.deleteOrgs(id, baseIdsList);
			resultInfoMap.put("id", id);
			resultInfoMap.put("baseIds", baseIdsList);
			if(StringUtils.isNotEmpty(parentId)) {
				service.updateHasChildColByPid(Integer.valueOf(parentId));
				resultInfoMap.put("parentId", parentId);
			}
		}

		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(resultInfoMap);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	// // 删除多个部门库
	// @SuppressWarnings("unchecked")
	// @ApiOperation(value = "删除部门库", httpMethod = "POST", response =
	// ArrayList.class, notes = "删除部门库")
	// @RequestMapping(value = "{ids}/delete", method = RequestMethod.POST)
	// public ResultPojo deleteOrganizationsByIds(HttpServletRequest request,
	// HttpServletResponse response,
	// @ApiParam(value = "一串部门库Id", required = false) @RequestParam(value =
	// "param", required = false) String param) {
	// List<Integer> ids = null;
	// try {
	// ids = JSON.toJavaObject((JSON) JSON.parse(param), ArrayList.class);
	// } catch (Exception e) {
	// // 参数异常时处理
	// return new ResultPojo(ResultPojo.CODE_FAILURE, "param : " + param + " is
	// not allow!", null);
	// }
	// service.delete(ids);
	// ResultPojo result = new ResultPojo();
	// result.setCode(ResultPojo.CODE_SUCCESS);
	// result.setResult(ids);
	// result.setMsg(param);
	// return result;
	// }

	// 根据参数查询部门库
	@ApiOperation(value = "根据参数查询部门库", httpMethod = "POST", response = OrganizationEntity.class, notes = "根据参数查询部门库")
	@RequestMapping(value = "Org", method = RequestMethod.POST)
	public ResultPojo findOrgByParam(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "根据参数查询部门库", required = false) @RequestBody OrganizationVo vo) {
		List<OrganizationEntity> orgs = null;
		orgs = service.findOrgsByParam(vo);
		ResultPojo result = new ResultPojo();
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(orgs);
		return result;
	}

	// 根据父部门标识查询第一级子部门库
	@ApiOperation(value = "根据父部门标识查询第一级子部门库", httpMethod = "GET", response = ArrayList.class, notes = "根据父部门标识查询第一级子部门库")
	@RequestMapping(value = "ChildOrgs/{parentId}", method = RequestMethod.GET)
	public ResultPojo findChildOrgs(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门库的父部门标识", required = false) @PathVariable("parentId") Integer parentId) {
		List<OrganizationEntity> orgs = service.findChildOrgs(parentId);
		ResultPojo result = new ResultPojo();
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(orgs);
		return result;
	}

	// 部门库调整顺序
	@ApiOperation(value = "部门库调整顺序", httpMethod = "POST", response = String.class, notes = "部门库调整顺序")
	@RequestMapping(value = "order", method = RequestMethod.POST)
	public ResultPojo sortOrgInfo(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门库的Id", required = false) @RequestBody Map<String, Object> param) {
		ResultPojo result = new ResultPojo();
		// 确保参数不能为空
		if (null == param) {
			result.setCode(ResultPojo.CODE_FAILURE);
			result.setResult(param);
			result.setMsg("参数为空 " + ResultPojo.MSG_FAILURE);
			return result;
		}
		
		// 被选中的部门库的ID
		Integer id = Integer.parseInt(param.get("id").toString());
		// 移动方向
		String sortDirection = param.get("sortDirection").toString();
		// 区域code
		String areaCode = param.get("areaCode").toString();
		
		String status = param.get("status").toString();
		
		Map<String, String> actionMsgMap = new HashMap<String,String>();
		if(DirectionEnum.up.toString().equals(sortDirection)) {
			actionMsgMap.put("msg", "对不起，向上不能移动，已达到最顶部位置。");
		} else {
			actionMsgMap.put("msg", "对不起，向下不能移动，已达到最底部位置。");
		}
		
		List<OrganizationEntity> orgs = getOrgOnSameLevel(id, areaCode,status);
		if (null == orgs) {
			result.setCode(ResultPojo.CODE_FAILURE);
			result.setResult(id);
			result.setMsg("获取同层级机构信息发生错误 " + ResultPojo.MSG_FAILURE);
			return result;
		}
		
		boolean findOrg = false;
		int i = 0;
		for (OrganizationEntity temp : orgs) {
			if (temp.getId().equals(id)) {
				findOrg = true;
			}
			if (findOrg && DirectionEnum.up.toString().equals(sortDirection)) {
				if(i-1<0){
					break;
				}
				actionMsgMap.put("currentSortValue", temp.getSort().toString());
				actionMsgMap.put("currentOrgId", temp.getId().toString());
				OrganizationEntity preOrg = orgs.get(i-1);
				Integer preSort = preOrg.getSort();
				actionMsgMap.put("preSortValue", preSort.toString());
				actionMsgMap.put("preOrgId", preOrg.getId().toString());
				preOrg.setSort(temp.getSort());
				temp.setSort(preSort);
				service.saveUpAndDownOrgInfo(temp, preOrg);
				actionMsgMap.put("msg", "向上移动成功。");
				
				break;
			}
			if (findOrg && DirectionEnum.down.toString().equals(sortDirection)) {
				if (i== (orgs.size() - 1)) {
					break;
				}
				actionMsgMap.put("currentSortValue", temp.getSort().toString());
				actionMsgMap.put("currentOrgId", temp.getId().toString());
				OrganizationEntity nextOrg = orgs.get(i+1);
				Integer nextSort = nextOrg.getSort();
				actionMsgMap.put("nextSortValue", nextSort.toString());
				actionMsgMap.put("nextOrgId", nextOrg.getId().toString());
				nextOrg.setSort(temp.getSort());
				temp.setSort(nextSort);
				service.saveUpAndDownOrgInfo(temp, nextOrg);
				actionMsgMap.put("msg", "向下移动成功。");
				break;
			}
			i++;
		}
		
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(actionMsgMap);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return result;
	}

	private List<OrganizationEntity> getOrgOnSameLevel(Integer id, String areaCode, String status) {
		if (id == null) {
			return null;
		}
		OrganizationEntity org = service.findById(id);
		if (null == org) {
			return null;
		}
		if (org.getParentId() == null) {
			List<OrganizationEntity> childOrgs = service.findOrgsByOwnSys(org.getOwnSys(), org.getType(), areaCode, status);
			return childOrgs;
		} else {
			List<OrganizationEntity> childOrgs = service.findByPidAndAreaCode(org.getParentId(), org.getOwnSys(),org.getType(), areaCode,status);
			return childOrgs;
		}
	}

	// 查询九大系统
	@ApiOperation(value = "查询九大系统", httpMethod = "POST", response = String.class, notes = "查询九大系统")
	@RequestMapping(value = "findOwnSys", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> findOwnSys(HttpServletRequest request, HttpServletResponse response) {
		return new ResponseEntity<ResultPojo>(new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS,
				dictionaryService.findDicByKey(OWN_SYS)), HttpStatus.OK);
	}

	// 统计地区的事业单位和行政机关
	@ApiOperation(value = "查询当前地区的行政机关和事业单位数量", httpMethod = "GET", response = ArrayList.class, notes = "查询当前地区的行政机关和事业单位数量，返回值中第一个为行政机关，第二个为事业单位")
	@RequestMapping(value = "CountXZJGAndSYDW/{areaCode}", method = RequestMethod.GET)
	public ResultPojo CountXZJGAndSYDW(HttpServletRequest request, HttpServletResponse response,
									   @ApiParam(value = "部门库的父部门标识", required = false) @PathVariable("areaCode") String areaCode) {
		Integer xzjg = service.countXZJG(areaCode);
		Integer sydw = service.countSYDW(areaCode);
		List<Integer> list = new ArrayList<Integer>();
		list.add(xzjg);
		list.add(sydw);
		ResultPojo result = new ResultPojo();
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(list);
		return result;
	}

	@ApiOperation(value = "检查所输入的部门名称是否已经存在", httpMethod = "POST", response = ArrayList.class, notes = "检查所输入的部门名称是否已经存在")
	@RequestMapping(value = "check/name", method = RequestMethod.POST)
	public ResultPojo checkOrgName(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门库的名称和区域code的map", required = false) @RequestBody Map<String, String> condMap) {
		// 声明返回结果
		ResultPojo result = new ResultPojo();
		String name = condMap.get("name");
		String areaCode = condMap.get("areaCode");
		String orgId = condMap.get("orgId");
		// 设定返回结果
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		result.setResult(service.checkOrgName(name,areaCode, orgId));
		return result;
	}

	@ApiOperation(value = "根据id获取机构树信息", httpMethod = "GET", response = OrganizationEntity.class, notes = "根据id获取机构树信息")
	@RequestMapping(value = "mapTree/{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findMapTreeById(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") Integer id) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();

		OrganizationEntity organizationEntity = service.findById(id);

		Map<String, Object> mapOrgTree = new HashMap<String, Object>();
		mapOrgTree.put("id", id);
		mapOrgTree.put("name", organizationEntity.getName());
		mapOrgTree.put("hrefFlag", "0");

		List<Map<String, Object>> childOrgMapList = new ArrayList<Map<String, Object>>();

		// ①内设机构信息取得
		// service调用
		DepartmentTreeNodeVo2  departmentTreeNodeVo2 = deptService.findMapTreeByBaseIdOpt(organizationEntity.getBaseId());
		// 追加内设机构的mapTree
		childOrgMapList.add(BeanUtils.transBean2Map(departmentTreeNodeVo2));
		// whm 事业单位没有下设机构
		if("1".equals(organizationEntity.getType())){
			// ②下设机构信息取得
			Map<String, Object> mapTreeXZJG = new HashMap<String, Object>();
			// service调用
			service.findMapTreeByCondition(organizationEntity, "1", mapTreeXZJG);
			// 追加下设机构的mapTree
			childOrgMapList.add(mapTreeXZJG);
		}

		// ③事业单位信息取得
		Map<String, Object> mapTreeSYDW = new HashMap<String, Object>();
		// service调用
		service.findMapTreeByCondition(organizationEntity, "2", mapTreeSYDW);
		// 追加事业单位的mapTree
		childOrgMapList.add(mapTreeSYDW);

		mapOrgTree.put("children", childOrgMapList);

		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(mapOrgTree);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	// 统计地区的事业单位和行政机关
	@ApiOperation(value = "查询当前地区的发布状态的行政机关和事业单位", httpMethod = "GET", response = ArrayList.class, notes = "查询当前地区的发布状态的行政机关和事业单位")
	@RequestMapping(value = "orgTree/{areaCode}", method = RequestMethod.GET)
	public ResultPojo findOrgTree(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "区划", required = false) @PathVariable("areaCode") String areaCode) {
		// 查询九大系统
		ResultPojo ownSysDics = JSON.toJavaObject(
				(JSON) JSON.parse(dictionaryService.findDicByKey(OWN_SYS).toJSONString()), ResultPojo.class);
		@SuppressWarnings("unchecked")
		List<Map<String, String>> dics = (List<Map<String, String>>) ownSysDics.getResult();
		// 查询部门库
		OrganizationVo vo = new OrganizationVo();
		vo.setAreaCode(areaCode);
		List<OrganizationEntity> orgInDBs = service.findOrgsByParam(vo);
		// 组成树结构
		Map<String, OrganizationTreeNodeVo> orgTreeNodeMap = new HashMap<String, OrganizationTreeNodeVo>();
		for (OrganizationEntity entity : orgInDBs) {
			// 过滤异常数据(部门库中的部门名字为null的部门)
			if(StringUtils.isEmpty(entity.getName())) {
				continue;
			}
			// 过滤异常数据(部门库中ParetnId为null且又不是主管部门的标示)
			if(entity.getParentId() == null && Contsants.OFS_ORGANIZATION_NOT_COMP.equals(entity.getIsComp())) {
				continue;
			}
			
			OrganizationTreeNodeVo treeNode = new OrganizationTreeNodeVo(entity);
			orgTreeNodeMap.put(treeNode.getId(), treeNode);
		}
		
		for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
			Integer parentId = treeNode.getParentId();
			// 组成树形结点时过滤掉异常数据（部门的ID和部门的parentId相等场合避免造成死循环）
			if(Integer.valueOf(treeNode.getId()).equals(parentId)) {
				continue;
			}
			if (parentId != null ) {
				if(orgTreeNodeMap.containsKey(parentId.toString())){
				orgTreeNodeMap.get(parentId.toString()).addChild(treeNode);
				}
			}
		}
		
		// 九大系统与部门组成树
		List<OrganizationTreeNodeVo> treeResult = new ArrayList<OrganizationTreeNodeVo>();
		for (Map<String, String> dic : dics) {
			OrganizationTreeNodeVo root = new OrganizationTreeNodeVo();
			root.setAreaCode(areaCode);
			root.setName(dic.get("name"));
			root.setId(dic.get("value"));
			Object sortObj = dic.get("sort");
			if (null != sortObj) {
				root.setSort((Integer) sortObj);
			}
			String ownSys = dic.get("value").toString();
			for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
				if (treeNode.getParentId() == null && ownSys.equals(treeNode.getOwnSys())) {
					root.addChild(treeNode);
				}
			}
			treeResult.add(root);
		}
		// 排序
		sort(treeResult);
		ResultPojo result = new ResultPojo();
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(treeResult);
		return result;
	}
	
	@ApiOperation(value = "查询当前地区已共享的的行政机关和事业单位", httpMethod = "GET", response = ArrayList.class, notes = "查询当前地区已共享的的行政机关和事业单位")
	@RequestMapping(value = "shared/orgTree/{areaCode}", method = RequestMethod.GET)
	public ResultPojo findSharedOrgTree(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "区划", required = false) @PathVariable("areaCode") String areaCode) {
		// 查询九大系统
		ResultPojo ownSysDics = JSON.toJavaObject(
				(JSON) JSON.parse(dictionaryService.findDicByKey(SHARED_OWN_SYS).toJSONString()), ResultPojo.class);
		@SuppressWarnings("unchecked")
		List<Map<String, String>> dics = (List<Map<String, String>>) ownSysDics.getResult();
		// 查询部门库
		OrganizationVo vo = new OrganizationVo();
		vo.setAreaCode(areaCode);
		List<OrganizationEntity> orgInDBs = service.findOrgsByParam(vo);
		// 组成树结构
		Map<String, OrganizationTreeNodeVo> orgTreeNodeMap = new HashMap<String, OrganizationTreeNodeVo>();
		for (OrganizationEntity entity : orgInDBs) {
			// 过滤异常数据(部门库中的部门名字为null的部门)
			if(StringUtils.isEmpty(entity.getName())) {
				continue;
			}
			// 过滤异常数据(部门库中ParetnId为null且又不是主管部门的标示)
			if(entity.getParentId() == null && Contsants.OFS_ORGANIZATION_NOT_COMP.equals(entity.getIsComp())) {
				continue;
			}
			
			OrganizationTreeNodeVo treeNode = new OrganizationTreeNodeVo(entity);
			orgTreeNodeMap.put(treeNode.getId(), treeNode);
		}
		
		for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
			Integer parentId = treeNode.getParentId();
			// 组成树形结点时过滤掉异常数据（部门的ID和部门的parentId相等场合避免造成死循环）
			if(Integer.valueOf(treeNode.getId()).equals(parentId)) {
				continue;
			}
			if (parentId != null ) {
				if(orgTreeNodeMap.containsKey(parentId.toString())){
				orgTreeNodeMap.get(parentId.toString()).addChild(treeNode);
				}
			}
		}
		
		// 九大系统与部门组成树
		List<OrganizationTreeNodeVo> treeResult = new ArrayList<OrganizationTreeNodeVo>();
		for (Map<String, String> dic : dics) {
			OrganizationTreeNodeVo root = new OrganizationTreeNodeVo();
			root.setAreaCode(areaCode);
			root.setName(dic.get("name"));
			root.setId(dic.get("value"));
			Object sortObj = dic.get("sort");
			if (null != sortObj) {
				root.setSort((Integer) sortObj);
			}
			String ownSys = dic.get("value").toString();
			for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
				if (treeNode.getParentId() == null && ownSys.equals(treeNode.getOwnSys())) {
					root.addChild(treeNode);
				}
			}
			treeResult.add(root);
		}
		// 排序
		sort(treeResult);
		ResultPojo result = new ResultPojo();
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(treeResult);
		return result;
	}

//	// 统计地区的事业单位和行政机关
//	@ApiOperation(value = "查询当前地区的行政机关和事业单位，状态可选", httpMethod = "GET", response = ArrayList.class, notes = "查询当前地区的行政机关和事业单位，状态可选")
//	@RequestMapping(value = "orgTree/{areaCode}/{status}", method = RequestMethod.GET)
//	public ResultPojo findOrgTreeWithStatus(HttpServletRequest request, HttpServletResponse response,
//			@ApiParam(value = "区划", required = false) @PathVariable("areaCode") String areaCode,
//			@ApiParam(value = "部门库的父部门标识", required = false) @PathVariable("status") String status) {
//		// 查询九大系统
//		ResultPojo ownSysDics = JSON.toJavaObject(
//				(JSON) JSON.parse(dictionaryService.findDicByKey(OWN_SYS).toJSONString()), ResultPojo.class);
//		@SuppressWarnings("unchecked")
//		List<Map<String, String>> dics = (List<Map<String, String>>) ownSysDics.getResult();
//		// 查询部门库
//		OrganizationVo vo = new OrganizationVo();
//		vo.setAreaCode(areaCode);
//		vo.setStatus(status);
//		List<OrganizationEntity> orgInDBs = service.findOrgsByParam(vo);
//		// 组成树结构
//		Map<String, OrganizationTreeNodeVo> orgTreeNodeMap = new HashMap<String, OrganizationTreeNodeVo>();
//		for (OrganizationEntity entity : orgInDBs) {
//			OrganizationTreeNodeVo treeNode = new OrganizationTreeNodeVo(entity);
//			orgTreeNodeMap.put(treeNode.getId(), treeNode);
//		}
//		for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
//			Integer parentId = treeNode.getParentId();
//			if (parentId != null && orgTreeNodeMap.containsKey(parentId)) {
//				orgTreeNodeMap.get(parentId).addChild(treeNode);
//			}
//		}
//		// 九大系统与部门组成树
//		List<OrganizationTreeNodeVo> treeResult = new ArrayList<OrganizationTreeNodeVo>();
//		for (Map<String, String> dic : dics) {
//			OrganizationTreeNodeVo root = new OrganizationTreeNodeVo();
//			root.setAreaCode(areaCode);
//			root.setName(dic.get("name"));
//			root.setId(dic.get("value"));
//			Object sortObj = dic.get("sort");
//			if (null != sortObj) {
//				root.setSort((Integer) sortObj);
//			}
//			String ownSys = dic.get("value").toString();
//			for (OrganizationTreeNodeVo treeNode : orgTreeNodeMap.values()) {
//				if (treeNode.getParentId() == null && ownSys.equals(treeNode.getOwnSys())) {
//					root.addChild(treeNode);
//				}
//			}
//			treeResult.add(root);
//		}
//		// 排序
//		sort(treeResult);
//		ResultPojo result = new ResultPojo();
//		result.setCode(ResultPojo.CODE_SUCCESS);
//		result.setResult(treeResult);
//		return result;
//	}

	@ApiOperation(value = "根据父部门标识查询第一级子部门库", httpMethod = "GET", response = ArrayList.class, notes = "根据父部门标识查询第一级子部门库")
	@RequestMapping(value = "{userId}/orgTree", method = RequestMethod.GET)
	public ResultPojo findOrgInfoByUserId(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门库的父部门标识", required = false) @PathVariable("userId") Integer userId) {
		
		ResultPojo result = new ResultPojo();
		OrganizationEntity  orgEntity = service.findOrgInfoByUserId(userId);
		if(null == orgEntity ){
			result.setCode(ResultPojo.CODE_NOT_BIND_ORG);
			result.setMsg("当前用户未绑定部门库信息，请通过用户管理进行部门库绑定。");
			result.setResult(null);
			return result;
		}
		Map<String, Object> orgTreeMap = new HashMap<String, Object>();
		orgTreeMap.put("areaCode", orgEntity.getAreaCode());
		orgTreeMap.put("id", orgEntity.getOwnSys());
		orgTreeMap.put("sort", 0);
		
		ResultPojo ownSysDics = JSON.toJavaObject(
				(JSON) JSON.parse(dictionaryService.findDicByKey(OWN_SYS).toJSONString()), ResultPojo.class);
		@SuppressWarnings("unchecked")
		List<Map<String, String>> dics = (List<Map<String, String>>) ownSysDics.getResult();
		String ownSysName = null;
		for (Map<String, String> dic : dics) {
			String ownSysValue = dic.get("value").toString();
			if(ownSysValue.equals(orgEntity.getOwnSys())) {
				ownSysName = dic.get("name");
				break;
			}
		}
		orgTreeMap.put("name", ownSysName);
		
		List<VHistOrgsInfo2Entity> vHistOrgsInfo2EntityAllList = new ArrayList<VHistOrgsInfo2Entity>();
		vHistOrgsInfo2EntityAllList = vHistOrgsInfo2Service.findByAreaIdOrderByOrgId(orgEntity.getAreaId());
		
		OrganizationVo vo = new OrganizationVo();
		vo.setAreaCode(orgEntity.getAreaCode());
		vo.setOwnSys(orgEntity.getOwnSys());
		List<OrganizationEntity> orgInDBs = service.findOrgsByParam(vo);
		// 组成树结构
		Map<String, OrganizationTreeNodeVo2> orgTreeNodeMap = new HashMap<String, OrganizationTreeNodeVo2>();
		for (OrganizationEntity entity : orgInDBs) {
			// 过滤异常数据(部门库中的部门名字为null的部门)
			if(StringUtils.isEmpty(entity.getName())) {
				continue;
			}
			// 过滤异常数据(部门库中ParetnId为null且又不是主管部门的标示)
			if(entity.getParentId() == null && Contsants.OFS_ORGANIZATION_NOT_COMP.equals(entity.getIsComp())) {
				continue;
			}
			
			OrganizationTreeNodeVo2 treeNode = new OrganizationTreeNodeVo2(entity);
			treeNode.setUserId(vHistOrgsInfo2Service.getWbjUserIdByConditon(entity.getId(), vHistOrgsInfo2EntityAllList ));
			orgTreeNodeMap.put(treeNode.getId(), treeNode);
		}
		OrganizationTreeNodeVo2 currentOrganizationTreeNodeVo = null;
		for (OrganizationTreeNodeVo2 treeNode : orgTreeNodeMap.values()) {
			Integer parentId = treeNode.getParentId();
			// 组成树形结点时过滤掉异常数据（部门的ID和部门的parentId相等场合避免造成死循环）
			if(Integer.valueOf(treeNode.getId()).equals(parentId)) {
				continue;
			}
			if(treeNode.getId().equals(orgEntity.getId().toString())) {
				currentOrganizationTreeNodeVo = treeNode;
			}
			
			
			if (parentId != null ) {
				if(orgTreeNodeMap.containsKey(parentId.toString())){
				orgTreeNodeMap.get(parentId.toString()).addChild(treeNode);
				}
			}
		}
		List<OrganizationTreeNodeVo2> childrenList = new ArrayList<OrganizationTreeNodeVo2>();
		if(null != currentOrganizationTreeNodeVo) {
			childrenList.add(currentOrganizationTreeNodeVo);
		}
		sort2(childrenList);		
		orgTreeMap.put("children", childrenList);
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		result.setResult(orgTreeMap);
		return result;
	}
	
	@ApiOperation(value = "批量保存或者更新部门库信息", httpMethod = "POST", notes = "批量保存或者更新部门库信息")
	@RequestMapping(value = "batchSaveOrUpdate", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> saveOrUpdateOrgInfoList(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "保存对象", required = true) @RequestBody List<OrganizationEntity> orgInfoList) throws Exception {
		
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		
		// 保存用户信息
		Map<String, Object> resultMap = service.SaveOrUpdateOrgInfoList(orgInfoList);
		if(null != resultMap.get("errInfo")) {
			// 结果集设定
			result.setCode(ResultPojo.CODE_FAILURE);
			result.setResult(resultMap);
			result.setMsg(ResultPojo.MSG_FAILURE +  resultMap.get("errInfo"));
		} else {
			result.setCode(ResultPojo.CODE_SUCCESS);
			result.setResult(resultMap);
			result.setMsg(ResultPojo.MSG_SUCCESS);
		}
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}
	
	private void sort(List<OrganizationTreeNodeVo> treeResult) {
		if (null == treeResult || treeResult.isEmpty()) {
			return;
		}
		Collections.sort(treeResult, new Comparator<OrganizationTreeNodeVo>() {
			@Override
			public int compare(OrganizationTreeNodeVo o1, OrganizationTreeNodeVo o2) {
				if (StringUtils.isEmpty(o2.getStatus())) {
					return 1;
				}
				if (StringUtils.isEmpty(o1.getStatus())) {
					return -1;
				}
				if (Integer.valueOf(o1.getStatus()) > Integer.valueOf(o2.getStatus())) {
					return 1;
				} else if (Integer.valueOf(o1.getStatus()) < Integer.valueOf(o2.getStatus())) {
					return -1;
				} else {
					if (StringUtils.isEmpty(o2.getType())) {
						return 1;
					}
					if (StringUtils.isEmpty(o1.getType())) {
						return -1;
					}
					if (Integer.valueOf(o1.getType()) > Integer.valueOf(o2.getType())) {
						return 1;
					} else if (Integer.valueOf(o1.getType()) < Integer.valueOf(o2.getType())) {
						return -1;
					} else {
						if (null == o2.getSort()) {
							return 1;
						}
						if (null == o1.getSort()) {
							return -1;
						}
						if (o1.getSort() > o2.getSort() ) {
							return 1;
						} else if(o1.getSort() < o2.getSort() ){
							return -1;
						} else {
							return 0;
						}
					}
				}
			}
		});

		for (OrganizationTreeNodeVo vo : treeResult) {
			sort(vo.getChildren());
		}
	}
	
	
	private void sort2(List<OrganizationTreeNodeVo2> treeResult) {
		if (null == treeResult || treeResult.isEmpty()) {
			return;
		}
		Collections.sort(treeResult, new Comparator<OrganizationTreeNodeVo2>() {
			@Override
			public int compare(OrganizationTreeNodeVo2 o1, OrganizationTreeNodeVo2 o2) {
				if (StringUtils.isEmpty(o2.getStatus())) {
					return 1;
				}
				if (StringUtils.isEmpty(o1.getStatus())) {
					return -1;
				}
				if (Integer.valueOf(o1.getStatus()) > Integer.valueOf(o2.getStatus())) {
					return 1;
				} else if (Integer.valueOf(o1.getStatus()) < Integer.valueOf(o2.getStatus())) {
					return -1;
				} else {
					if (StringUtils.isEmpty(o2.getType())) {
						return 1;
					}
					if (StringUtils.isEmpty(o1.getType())) {
						return -1;
					}
					if (Integer.valueOf(o1.getType()) > Integer.valueOf(o2.getType())) {
						return 1;
					} else if (Integer.valueOf(o1.getType()) < Integer.valueOf(o2.getType())) {
						return -1;
					} else {
						if (null == o2.getSort()) {
							return 1;
						}
						if (null == o1.getSort()) {
							return -1;
						}
						if (o1.getSort() > o2.getSort() ) {
							return 1;
						} else if(o1.getSort() < o2.getSort() ){
							return -1;
						} else {
							return 0;
						}
					}
				}
			}
		});

		for (OrganizationTreeNodeVo2 vo : treeResult) {
			sort2(vo.getChildren());
		}
	}

	private static final String OWN_SYS = "ownsys";
	private static final String SHARED_OWN_SYS = "sharedOwnsys";
}

enum DirectionEnum {
	up(), down();
}
